package com.middlegroup.payadmin.controller.sys;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.middlegroup.common.annotation.AllLog;
import com.middlegroup.common.enums.*;
import com.middlegroup.common.enums.ServiceType;
import com.middlegroup.common.exception.BusinessException;
import com.middlegroup.payadmin.controller.BaseController;
import com.middlegroup.payadmin.mapper.ChannelsMapper;
import com.middlegroup.payadmin.pojo.dto.ChannelsDto;
import com.middlegroup.payadmin.pojo.dto.DataGrid;
import com.middlegroup.payadmin.pojo.message.ApiResult;
import com.middlegroup.payadmin.pojo.po.*;
import com.middlegroup.payadmin.service.MerchantService;
import com.middlegroup.payadmin.service.MerchantSubjectChannelRouterService;
import com.middlegroup.payadmin.service.SubjectChannelsService;
import com.middlegroup.payadmin.service.SubjectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Set;

/**
 *
 * @author pc
 * @date 2019/1/22
 */
@Controller
@RequestMapping("/sys/merchant")
@Api(value = "商户管理", description = "商户管理", tags = "1.2")
@Valid
public class MerchantController extends BaseController {

    @Resource
    private MerchantService merchantService;

    @Resource
    private SubjectService subjectService;

    @Resource
    private SubjectChannelsService subjectChannelsService;

    @Resource
    private MerchantSubjectChannelRouterService merchantSubjectChannelRouterService;

    @Resource
    private RedisTemplate redisCacheTemplate;

    @Resource
    private ChannelsMapper channelsMapper;

    @ApiIgnore
    @GetMapping("/list")
    public String list() {
        return "sys/merchant/list";
    }


    @ApiOperation(value = "带条件分页查询商户列表")
    @GetMapping(value = "/query")
    @ResponseBody
    public PageInfo<Merchant> query(DataGrid grid, Merchant merchant) {
        return merchantService.getMerchantList(grid,merchant);
    }

    @ApiIgnore
    @GetMapping(value = "/edit")
    public String edit(Long id) {

        Merchant merchant = merchantService.selectById(id);
        request.setAttribute("dto",merchant);
        //查询所有主体，方便绑定
        List<Subject> subjectList = subjectService.selectList(null);
        request.setAttribute("subjectList",subjectList);
        return "sys/merchant/edit";
    }

    @ApiOperation(value = "添加/修改商户信息")
    @AllLog(module = "商户管理", methods = "保存商户", description = "添加/修改商户信息")
    @PostMapping(value = "/save")
    @ResponseBody
    @Transactional(readOnly = false)
    public ApiResult<Merchant> save(Merchant dto) {

        //商户路由绑定
        if (StringUtils.isNotBlank(dto.getSelectCode())){
            String[] lineArr = dto.getSelectCode().split(",");
            for (String line : lineArr){
                String[] channelCodeArr = line.split("\\|");
                String channelCode = channelCodeArr[0];
                String weightStr = channelCodeArr[1];
                String levelStr = channelCodeArr[2];
                Integer weight = 0;
                Integer level = 1;
                if (StringUtils.isNotBlank(weightStr)){
                    weight = Integer.valueOf(weightStr);
                }
                if (StringUtils.isNotBlank(levelStr)){
                    level = Integer.valueOf(levelStr);
                }
                MerchantSubjectChannelRouter merchantSubjectChannelRouter = new MerchantSubjectChannelRouter();
                merchantSubjectChannelRouter.setSubjectCode(dto.getSubjectCode());
                merchantSubjectChannelRouter.setChannelCode(channelCode);
                merchantSubjectChannelRouter.setWeight(weight);
                merchantSubjectChannelRouter.setLevel(level);
                merchantSubjectChannelRouter.setMerchantCode(dto.getCode());
                merchantSubjectChannelRouterService.saveOrUpdate(merchantSubjectChannelRouter);
            }
        }

        if (StringUtils.isNotBlank(dto.getUnselectCode())){
            //删除排除的路由
            String[] unselectCodeArr = dto.getUnselectCode().split(",");
            for (String unselectCode : unselectCodeArr){
                EntityWrapper<MerchantSubjectChannelRouter> entityWrapper = new EntityWrapper<>();
                entityWrapper.where("merchant_code={0} and channel_code={1} and subject_code={2}",dto.getCode(),unselectCode,dto.getSubjectCode());
                merchantSubjectChannelRouterService.delete(entityWrapper);
            }
        }

        //删除redis中缓存记录
        Set<String> keys = redisCacheTemplate.keys("middle_pay:router:*");
        if (CollectionUtils.isNotEmpty(keys)) {
            redisCacheTemplate.delete(keys);
        }

        if (dto.getId() != null) {
            return ApiResult.getResponse(this.merchantService.updateById(dto));
        }
        //校验商户编号是否可用
        EntityWrapper<Merchant> entityWrapper = new EntityWrapper<>();
        entityWrapper.where("code={0}",dto.getCode());
        Merchant merchant = merchantService.selectOne(entityWrapper);
        if (null != merchant){
            return ApiResult.getFailure("商户编码已存在，请更换!");
        }
        return ApiResult.getResponse(this.merchantService.insert(dto));
    }

    @ApiOperation(value = "根据主体code和通道类型获取该主体目前的渠道绑定信息")
    @GetMapping(value = "/getSubjectChannels")
    @ResponseBody
    public List<ChannelsDto> getSubjectChannels(String serviceType,@NotNull(message = "主体编码不能为空!")  String subjectCode ,String code) {
        List<ChannelsDto> channelsList =  this.subjectChannelsService.getChannelsBySubjectCode(serviceType,subjectCode,code);

        return channelsList;
    }
}
